<template>
  <n-card :bordered="false" class="proCard">
    <el-button type="primary" @click="tianjia">追加类目</el-button>
    <el-tree
      @node-click="handleNodeClick"
      :data="dataSource"
      show-checkbox
      node-key="id"
      default-expand-all
      accordion
      :expand-on-click-node="false"
    >
      <template #default="{ node, data }">
        <span class="custom-tree-node">
          <el-input v-model="data.label" placeholder="请输入" />
          <span style="color: #2d8cf0" class="mr-3" @click="append(data)">添加</span>
          <span style="color: #ff5959" @click="remove(node,data)">删除</span>
        </span>
      </template>
    </el-tree>
  </n-card>
</template>

<script lang="ts" setup>
  import { ref } from 'vue';
  import type Node from 'element-plus/es/components/tree/src/model/node';

  interface Tree {
    id: number;
    label: string;
    children?: Tree[];
  }
  let id = 1000;

  const append = (data: Tree) => {
    console.log(data)
    const newChild = { id: id++, label: '', children: [] };
    if (!data.children) {
      data.children = [];
    }
    data.children.push(newChild);
    dataSource.value = [...dataSource.value];
  };

  const remove = (node: Node, data: Tree) => {
    const parent = node.parent;
    const children: Tree[] = parent.data.children || parent.data;
    const index = children.findIndex((d) => d.id === data.id);
    children.splice(index, 1);
    dataSource.value = [...dataSource.value];
  };

  const dataSource = ref<Tree[]>([
    {
      id: 1,
      label: '一级',
    },
  ]);
  const tianjia = () => {
    dataSource.value.push({
      id: 0,
      label: '',
    });
  };
</script>

<style lang="less" scoped>
  .custom-tree-node {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: space-between;
    font-size: 14px;
    padding-right: 8px;
  }
  :deep(.el-input__inner) {
    height: 25px;
    line-height: 25px;
  }
  :deep(.el-tree-node__content) {
    width: 300px;
    margin-top: 5px;
  }
  :deep(.el-input__wrapper) {
    margin-right: 5px;
  }
  :deep(.el-tree-node) {
    padding-bottom: 5px;
  }
  :deep(.el-tree) {
    margin-top: 20px;
  }
  :deep(.el-link__inner) {
    margin-right: 10px;
  }
</style>
